package service

import (
	"github.com/TarsCloud/TarsGo/tars"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/wzh200x/hyperNexus/hyperNexusCommon"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/commonProtocol"
	Server "github.com/wzh200x/webServer/server"
)

// 用户信息结构
type User struct {
	ID                 uint    `json:"id"`
	Username           string  `json:"username"`
	AvatarID           int     `json:"avatarId"`
	HyperNexusAvatarId int64   `json:"hyperNexusAvatarId"`
	AvatarIds          []int64 `json:"avatarIds"`
	LoginTime          string  `json:"loginTime"`
	LogoutTime         string  `json:"logoutTime"`
	CreateTime         string  `json:"createdTime"`
}

// 登录请求结构
type AuthRequest struct {
	Username             string `json:"username" form:"username" binding:"required"`
	Password             string `json:"password" form:"password" binding:"required"`
	ThirdPlatformType    int    `json:"thirdPlatformType" form:"thirdPlatformType"`       // 平台类型
	ThirdPlatform        string `json:"thirdPlatform" form:"thirdPlatform"`               // 平台名称
	ThirdAccount         string `json:"thirdAccount" form:"thirdAccount"`                 // 第三方账号
	ThirdToken           string `json:"thirdToken" form:"thirdToken"`                     // 第三方令牌
	ThirdTokenExpireTime int64  `json:"thirdTokenExpireTime" form:"thirdTokenExpireTime"` // 令牌过期时间
	ThirdCode            string `json:"thirdCode" form:"thirdCode"`                       // 授权码
	ThirdSessionKey      string `json:"thirdSessionKey" form:"thirdSessionKey"`           // 会话密钥
}

// 登录响应结构
type AuthResponse struct {
	Token           string `json:"token"`
	TokenExpireTime int64  `json:"tokenExpireTime"` // 令牌过期时间戳
	User            User   `json:"user"`
}

// 验证用户登录
func AuthenticateUser(authReq AuthRequest) (*AuthResponse, error) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()
	// 构建查询参数
	accountQuery := commonProtocol.AccountQuery{
		AccountName: authReq.Username,
	}

	// 查询账号是否存在
	account, queryErr := dbAgentClient.QueryAccount(accountQuery)
	if queryErr != nil {
		// 账号不存在，创建新账号
		if queryErr.Error() == "record not found" {
			// 创建新账号
			newAccount := commonProtocol.Account{
				AccountName: authReq.Username,
				PassWord:    authReq.Password,
			}

			// 如果是第三方平台登录
			if authReq.ThirdPlatformType > 0 {
				newAccount.ThirdPlatformType = gconv.Int32(authReq.ThirdPlatformType)
				newAccount.ThirdPlatform = authReq.ThirdPlatform
				newAccount.ThirdAccount = authReq.Username // 使用accountName作为thirdAccount
				newAccount.ThirdToken = authReq.ThirdToken
				newAccount.ThirdTokenExpireTime = authReq.ThirdTokenExpireTime
				newAccount.ThirdSessionKey = authReq.ThirdSessionKey
			}

			// 调用DbAgentServer创建账号
			createdAccount, createErr := dbAgentClient.CreateAccount(newAccount)
			if createErr != nil {
				return nil, createErr
			}

			// 生成JWT令牌
			token, expireTime, tokenErr := GenerateToken(uint(createdAccount.ID), createdAccount.AccountName)
			if tokenErr != nil {
				return nil, tokenErr
			}

			// 返回令牌和用户信息
			return &AuthResponse{
				Token:           token,
				TokenExpireTime: expireTime,
				User: User{
					ID:                 uint(createdAccount.ID),
					Username:           createdAccount.AccountName,
					AvatarID:           int(createdAccount.AvatarId),
					HyperNexusAvatarId: createdAccount.HyperNexusAvatarId,
					AvatarIds:          createdAccount.AvatarIds,
					LoginTime:          createdAccount.LoginTime,
					LogoutTime:         createdAccount.LogoutTime,
					CreateTime:         createdAccount.CreateTime,
				},
			}, nil
		}
		return nil, queryErr
	}

	// 账号存在，验证密码
	if account.PassWord != authReq.Password {
		return nil, nil // 返回nil表示密码错误
	}

	// 更新登录时间
	account.LoginTime = hyperNexusCommon.GetCurrentTimeString()
	// 调用DbAgentServer更新账号
	_, updateErr := dbAgentClient.UpdateAccount(account)
	if updateErr != nil {
		// 密码验证通过但更新失败，记录错误但仍然允许登录
		tars.GetLogger("").Errorf("更新账号登录时间失败: %v", updateErr)
	}

	// 生成JWT令牌
	token, expireTime, tokenErr := GenerateToken(uint(account.ID), account.AccountName)
	if tokenErr != nil {
		return nil, tokenErr
	}

	// 返回令牌和用户信息
	return &AuthResponse{
		Token:           token,
		TokenExpireTime: expireTime,
		User: User{
			ID:                 uint(account.ID),
			Username:           account.AccountName,
			AvatarID:           int(account.AvatarId),
			HyperNexusAvatarId: account.HyperNexusAvatarId,
			AvatarIds:          account.AvatarIds,
			LoginTime:          account.LoginTime,
			LogoutTime:         account.LogoutTime,
			CreateTime:         account.CreateTime,
		},
	}, nil
}
